//
//  Api.swift
//  ptbuy
//
//  Created by MyMac on 2024/12/3.
//
import Foundation
class  NetworkApi {
    
    static let shared = NetworkApi()
    
    private let baseURL  = "http://www.pengtushuzhi.com/ptbuyht"
    

       // 通用 GET 请求方法
    func fetchData(from endpoint: String,parameters:[String:String], completion: @escaping (Data?, Error?) -> Void) {
           
           if let validURL = URL(string: "\(baseURL)/\(endpoint)") {
               
               // 构建查询字符串
               var urlComponents = URLComponents(string: "\(baseURL)/\(endpoint)")!
               urlComponents.queryItems = parameters.map { key, value in
                   URLQueryItem(name: key, value: value)
               }
               var request = URLRequest(url: urlComponents.url!)
               request.httpMethod = "GET"
              
               
               
               let task = URLSession.shared.dataTask(with: request) { data, response, error in
                   completion(data, error)
               }
               task.resume()
           } else {
               completion(nil,nil)
           } 
       }
       
       // 通用 POST 请求方法
       func postData(to endpoint: String, body: Data, completion: @escaping (Data?, Error?) -> Void) {
          
           if let validURL = URL(string: "\(baseURL)/\(endpoint)") {
               var request = URLRequest(url: validURL)
               request.httpMethod = "POST"
               request.httpBody = body
               
               let task = URLSession.shared.dataTask(with: request) { data, response, error in
                   completion(data, error)
               }
               task.resume()
           } else {
               completion(nil,nil)
           }
          
       }
    
}
